<%--
  Created by IntelliJ IDEA.
  User: fan
  Date: 2025/10/16
  Time: 10:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<style>
    .card {
        border-radius: 0.5rem;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
        border: none;
        margin-bottom: 1.5rem;
    }
</style>

<jsp:include page="header.jsp"/>
<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3><i class="fas fa-tasks"></i> 考试管理</h3>
    </div>

    <!-- 卡片中的搜索部分 -->
    <div class="card fade-in search-card">
        <div class="card-body">
            <form action="${pageContext.request.contextPath}/examManage/searchExam" method="get" id="searchForm">
                <div class="row g-3 align-items-center">
                    <div class="col-md-3">
                        <select class="form-select" name="searchType">
                            <option value="examName" ${searchType eq 'examName' ? 'selected' : ''}>按考试名称搜索
                            </option>
                            <option value="authorId" ${searchType eq 'authorId' ? 'selected' : ''}>按作者ID搜索</option>
                            <option value="courseId" ${searchType eq 'courseId' ? 'selected' : ''}>按课程ID搜索</option>
                        </select>
                    </div>
                    <div class="col-md-5">
                        <!-- 搜索框结构 -->
                        <div class="search-box position-relative">
                            <input type="text" class="form-control ps-5" placeholder="输入搜索内容"
                                   id="examSearchInput" name="examSearchText" value="${examSearchText}">
                            <i class="bi bi-search position-absolute"
                               style="left: 15px; top: 50%; transform: translateY(-50%);"></i>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="search-actions d-flex gap-2">
                            <button class="btn btn-primary" type="submit" id="searchBtn">
                                <i class="bi bi-search"></i> 查询
                            </button>
                            <button class="btn btn-success" type="button" data-bs-toggle="modal"
                                    data-bs-target="#examModal">
                                <i class="bi bi-plus-circle"></i> 新增考试场次
                            </button>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>


    <!-- 考试场次列表 -->
    <div class="card">
        <div class="card-body">
            <table class="table table-hover table-striped">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>考试名称</th>
                    <th>开始时间</th>
                    <th>持续时间(分钟)</th>
                    <th>作者</th>
                    <th>课程</th>
                    <th>创建日期</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <c:set var="examList" value="${requestScope.examinations}"/>
                <c:if test="${empty examList}">
                    <tr>
                        <td colspan="9" class="text-center">暂无考试数据</td>
                    </tr>
                </c:if>
                <c:forEach var="exam" items="${examinations}">
                    <tr>
                        <td>${exam.id}</td>
                        <td>${exam.examName}</td>
                        <td>${exam.startTime}</td>
                        <td>${exam.duration}</td>
                        <td>${exam.authorName}</td>
                        <td>${exam.courseName}</td>
                        <td>${exam.createDate}</td>
                        <td>
                            <c:choose>
                                <c:when test="${exam.state == 0}">
                                    <span class="badge bg-secondary">未开始</span>
                                </c:when>
                                <c:when test="${exam.state == 1}">
                                    <span class="badge bg-success">进行中</span>
                                </c:when>
                                <c:when test="${exam.state == 2}">
                                    <span class="badge bg-primary">已结束</span>
                                </c:when>
                                <c:otherwise>
                                    <span class="badge bg-light">未知状态</span>
                                </c:otherwise>
                            </c:choose>
                        </td>
                        <td>
                            <c:choose>
                                <c:when test="${exam.state == 0}">
                                    <button class="btn btn-sm btn-success">开始考试</button>
                                    <button class="btn btn-sm btn-info" data-bs-toggle="modal"
                                            data-bs-target="#examModal" data-id="${exam.id}">编辑
                                    </button>
                                    <button class="btn btn-sm btn-danger" data-bs-toggle="modal"
                                            data-bs-target="#deleteConfirmModal">删除
                                    </button>
                                </c:when>
                                <c:when test="${exam.state == 1}">
                                    <button class="btn btn-sm btn-warning">结束考试</button>
                                    <button class="btn btn-sm btn-info" disabled>编辑</button>
                                    <button class="btn btn-sm btn-danger" disabled>删除</button>
                                </c:when>
                                <c:otherwise>
                                    <button class="btn btn-sm btn-secondary" disabled>已结束</button>
                                    <button class="btn btn-sm btn-info" disabled>编辑</button>
                                    <button class="btn btn-sm btn-danger" data-bs-toggle="modal"
                                            data-bs-target="#deleteConfirmModal">删除
                                    </button>
                                </c:otherwise>
                            </c:choose>
                        </td>
                    </tr>
                </c:forEach>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- 新增/编辑考试 模态框 (Modal) -->
<div class="modal fade" id="examModal" tabindex="-1" aria-labelledby="examModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="examModalLabel">新增/编辑考试</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="examModal" action="examServlet?action=save" method="post">
                    <input id="examId" type="hidden" name="examId" value=""> <%-- 编辑时需要 examId --%>
                    <div class="mb-3">
                        <label for="examName" class="form-label">考试名称</label>
                        <input type="text" class="form-control" id="examName" name="examName" required>
                    </div>
                    <div class="mb-3">
                        <label for="startTime" class="form-label">开始时间</label>
                        <input type="datetime-local" class="form-control" id="startTime" name="startTime" required>
                    </div>
                    <div class="mb-3">
                        <label for="duration" class="form-label">考试时长（分钟）</label>
                        <input type="number" class="form-control" id="duration" name="duration" required>
                    </div>
                    <div class="mb-3">
                        <label for="paperId" class="form-label">关联试卷</label>
                        <select class="form-select" id="paperId" name="paperId" required>
                            <option selected disabled value="">请选择试卷...</option>
                            <%-- 动态加载试卷列表 --%>
                            <c:forEach items="${requestScope.paperTemplates}" var="paperTemplate">
                                <option value="${paperTemplate.id}">${paperTemplate.templateName}</option>
                            </c:forEach>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="participants" class="form-label">关联课程</label>
                        <select class="form-select" id="participants" name="participants" required>
                            <option selected disabled value="">请选择课程...</option>
                            <%-- 动态加载课程列表 --%>
                            <c:forEach items="${requestScope.courses}" var="course">
                                <option value="${course.id}">${course.name}</option>
                            </c:forEach>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button class="btn btn-primary" id="saveExam">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认 模态框 -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                您确定要删除这场考试吗？此操作不可恢复。
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <a href="examServlet?action=delete&id=..." class="btn btn-danger">确定删除</a>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        const $saveExamBtn = $("#saveExam");
        const $examModal = $("#examModal");
        // 初始化模态框标题为"新增考试"
        $("#examModalLabel").text("新增考试");

        // 将时间戳转换为datetime-local格式 (YYYY-MM-DDTHH:mm)
        function formatTimestampToDateTimeLocal(timestamp) {
            var date = new Date(timestamp);
            var year = date.getFullYear();
            var month = ('0' + (date.getMonth() + 1)).slice(-2);
            var day = ('0' + date.getDate()).slice(-2);
            var hours = ('0' + date.getHours()).slice(-2);
            var minutes = ('0' + date.getMinutes()).slice(-2);

            return year + '-' + month + '-' + day + 'T' + hours + ':' + minutes;
        }

        // 监听模态框显示事件
        $examModal.on("show.bs.modal", function (event) {
            let button = $(event.relatedTarget);
            let examId = button.data("id");

            // 获取模态框内的表单元素
            let modal = $(this);
            let form = modal.find('form');

            // 清空表单数据
            form[0].reset();
            form.find('input[type="hidden"][name="examId"]').val('');

            if (examId) {
                // 如果有examId，则为编辑模式
                $("#examModalLabel").text("编辑考试");

                $.ajax({
                    url: "teaexammanage/edit?examId=" + examId,
                    type: "GET",
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                        modal.find('#examName').val(data.examName);
                        // 使用转换函数处理时间戳
                        modal.find('#startTime').val(formatTimestampToDateTimeLocal(data.startTime));
                        modal.find('#duration').val(data.duration);
                        modal.find('#paperId').val(data.paperId);
                        modal.find('#participants').val(data.courseId);
                        modal.find('input[type="hidden"][name="examId"]').val(data.id);
                    },
                    error: function (xhr, status, error) {
                        console.log(error);
                    }
                })
            } else {
                // 如果没有examId，则为新增模式
                $("#examModalLabel").text("新增考试");
            }
        });

        // 监听模态框取消按钮点击事件，清空表单
        $examModal.on("hidden.bs.modal", function () {
            var form = $(this).find('form');
            form[0].reset();
            form.find('input[type="hidden"][name="examId"]').val('');
            // 重置下拉框为默认选项
            form.find('select').each(function () {
                $(this).find('option:first').prop('selected', true);
            });
        });

        // 监听保存按钮点击事件
        $saveExamBtn.click(() => {
            console.log("保存按钮点击事件")
            // 1. 获取表单数据
            let examId = null;
            const examName = $examModal.find("#examName").val();
            const startTime = formatTimestampToDateTimeLocal($examModal.find("#startTime").val());
            const duration = $examModal.find("#duration").val();
            const templateId = $examModal.find("#paperId").val();
            const courseId = $examModal.find("#participants").val();
            console.log($examModal.find("#participants"))
            console.log($examModal.find("#paperId"))
            console.log(examId, examName, startTime, duration, templateId, courseId)
            // 2. 调用生成试卷接口
            $.post("http://localhost:8080/examproject/teaexammanage/add", {
                examName,
                startTime,
                duration,
                courseId,
            }, null, "json").done(result => {
                console.log("哈哈" + result);
                if (result.code) {
                    console.log("哈哈" + result);
                    const match = result.message.match(/examId:(\d+)/);
                    if (match && match[1]) {
                        examId = parseInt(match[1]);
                        console.log("提取到的examId:", examId);
                        // 3. 调用生成考试接口
                        $.post("http://localhost:8080/examproject/examQuestionRela/autoGenerate", {
                            examId,
                            templateId,
                        }, null, "json").done(
                            innerResult => {
                                console.log("嘿嘿" + innerResult);
                                if (innerResult.code) {
                                    alert(innerResult.message);
                                }
                                alert(innerResult.message)
                                window.location.reload();
                            }
                        ).fail((xhr, status, e) => {
                            console.log("嘿嘿");
                            alert(e.message)
                        });
                    }
                    alert("生成试卷成功" + result.message);
                }
                alert(result.message)
            }).fail((xhr, status, e) => {
                console.log("哈哈");
                alert(e.message)
            });
        });
    });
</script>
<jsp:include page="footer.jsp"/>


